<template>
  <el-dialog :modelValue="show" title="玩家信息" :close-on-click-modal="false" :close-on-press-escape="false"  :destroy-on-close="true" width="70%"
    top="12vh" @close="handleClose">
    <div class="dialogMax">
      <div v-loading="data.loadingInfo" class="border-line" style="padding: 15px 10px;">
        <div class="flexBetween marginB20" >
          <div class="box-title flex">
            【 <span class="mustPass">{{ props.checkedItem.uid }}</span> 】<span class="mustPass marginR5">{{ data.userInfo.account3d }} </span> 基础信息
            <div class="flex marginL10" v-if="selectToLabel(indexStore.agentArray, props.checkedItem.agent_id,'isOpenTestUser','value')">
              <el-select v-model="data.userInfo.test_type" placeholder="请选择" filterable >
                <el-option v-for="item in PlayerType" :disabled="(!item.value && data.userOldInfo.test_type)?true:false" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button class="marginL5" type="danger" @click="setUserType">设置类型</el-button>
            </div>
          </div>
          <el-button type="success" @click="refresh">刷 新</el-button>
        </div>
        <div class="flexStartDetween">
          <!-- 玩家详情 -->
          <div class="width50 flexWrapDownRight">
            <div v-for="(item, index) in data.fields" :key="index" :class="item.show ? 'showColor width50' : 'width50'"
              class="itemData flex textCenter">
              <div class="width40 text-cut">{{ item.label }}</div>
              <div class="width60 text-cut"
                :class="item.label == '今日输赢' || item.label == '三日输赢' || item.label == '历史输赢' ? colorClass(item.value) : item.label == '当前状态' ? colorClass(data.userInfo.is_online) : ''">
                {{ item.value }}
              </div>
            </div>
          </div>
          <!-- 游戏详情 -->
          <div class="width50 paddingL10" style="position: relative;">
            <div class="dataType">
              <el-tabs v-model="data.detailType" type="card" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="历史信息" :name="1" />
                <el-tab-pane label="投注行为" :name="2" />
              </el-tabs>
            </div>
            <div class="flex marginB5">
              游戏筛选:
              <el-select class="marginL5 marginR5" v-model="data.gameType" placeholder="请选择" filterable
                @change="chooseGame">
                <el-option label="全部" :value="-1" />
                <el-option v-for="(item, index) in indexStore.gameArray" :key="index" :label="'【' + item.value + '】' + item.label"
                  :value="item.value" />
              </el-select>
              <div class="flex" v-if="data.detailType == 2 ? true : false">
                <el-button size="default" :type="data.dayTableIndex == 1 ? 'success' : ''" :disabled="indexStore.loading"
                  @click="changeTableTime(1)">今日</el-button>
                <el-button size="default" :type="data.dayTableIndex == 2 ? 'success' : ''" :disabled="indexStore.loading"
                  @click="changeTableTime(2)">昨日</el-button>
                <el-button size="default" :type="data.dayTableIndex == 4 ? 'success' : ''" :disabled="indexStore.loading"
                  @click="changeTableTime(4)">本周</el-button>
                <el-button size="default" :type="data.dayTableIndex == 5 ? 'success' : ''" :disabled="indexStore.loading"
                  @click="changeTableTime(5)">本月</el-button>
                <el-button size="default" :type="data.dayTableIndex == 6 ? 'success' : ''" :disabled="indexStore.loading"
                  @click="changeTableTime(6)">上月</el-button>
              </div>
            </div>
            <div class="contentData">
              <el-table ref="tableRef" :data="data.detailType==1?data.gameList:data.gearList" border @sort-change="sortTable"
                style="width: 100%;height: 338px;">
                <template v-for="(item, index) in data.gearFields" :key="index">
                  <el-table-column v-if="(item.detailType == data.detailType && item.show)?true:false" :prop="item.prop" :label="item.label" :width="item.width" 
                   :sortable="item.sort ? true : false" show-overflow-tooltip>
                   <template #header>
                    <el-tooltip v-if="item.tips" effect="dark" placement="top">
                      <template #content>
                        {{ item.tips }}
                      </template>
                      <el-icon class="ques-tips">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                    {{ item.label }}
                  </template>
                    <template v-if="item.prop == 'game_id'" #default="scope">
                      {{ selectToLabel(indexStore.gameArray, scope.row.game_id) }}
                    </template>
                    <template v-if="item.prop == 'total_bet'" #default="scope">
                      <span class="colorText">{{ BigWan(scope.row.total_bet) }}</span>
                    </template>
                    <template v-if="item.prop == 'total_game_income'" #default="scope">
                      <span :class="colorClass(scope.row.total_game_income)">{{ BigWan(scope.row.total_game_income)  }}</span>
                    </template>
                    <template v-if="item.prop == 'rtp'" #default="scope">
                      {{ scope.row.rtp }}%
                    </template>
                    <template v-if="item.prop == 'percentage'" #default="scope">
                      <span class="colorText">{{ BigWan(scope.row.sum_bet) }} / <span class="colorRed">{{ BigPercent(scope.row.sum_bet,data.total_bet) }}</span></span>
                    </template>
                    <template v-if="item.prop == 'user_gear'" #default="scope">
                      <span class="marginR2" v-for="(item,index) in scope.row.user_gear" :key="index">
                        {{ BigWan(item.bet) }}<span v-if="index!=scope.row.user_gear.length-1">,</span>
                      </span>
                    </template>
                    <template v-if="item.prop == 'proportion'" #default="scope">
                      <span class="marginR2" v-for="(item,index) in scope.row.user_gear" :key="index">
                        {{ BigPercent(item.bet_count,scope.row.sum_bet_count) }}<span v-if="index!=scope.row.user_gear.length-1">,</span>
                      </span>
                    </template>
                    <template v-if="item.prop == 'total_income'" #default="scope">
                      <span :class="colorClass(scope.row.total_income)">{{ BigWan(scope.row.total_income) }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <!-- 玩家资产变动走势 -->
      <div class="border-line" v-loading="data.loadingChart">
        <el-form :model="data" :inline="true">
          <el-form-item label="日期时间：">
            <el-date-picker v-model="data.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
          </el-form-item>
          <el-form-item label="游戏：">
            <el-select v-model="data.game_id" placeholder="请选择" filterable>
              <el-option label="全部" :value="-1" />
              <el-option v-for="item in indexStore.gameArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="getGoldList">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="flex" style="margin-top: -15px;margin-bottom: 5px;">
          <el-button :type="data.dayIndex == 1 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(1)">今日</el-button>
          <el-button :type="data.dayIndex == 2 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(2)">昨日</el-button>
          <el-button :type="data.dayIndex == 3 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(3)">上周</el-button>
          <el-button :type="data.dayIndex == 4 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(4)">本周</el-button>
          <el-button :type="data.dayIndex == 5 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(5)">本月</el-button>
          <el-button :type="data.dayIndex == 6 ? 'success' : ''" :disabled="indexStore.loading"
            @click="changeTime(6)">上月</el-button>
        </div>
        <LargeCharts chartTitle="玩家资产变动走势" :xAxisData="data.onlineXAxis" :seriesData="data.onlineSeries" />
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import LargeCharts from '@/components/Echarts/largeChart.vue'
import { getDateDay, getWeek, getMonth, setTimeValue, setTimestampTime } from '@/utils/time'
import { OnlineState, PlayerType } from '@/config/eunm'
import { throttle, selectToLabel, colorClass, sortObjectArray, ArrayReduce } from '@/utils/index'
import { BigWan, BigPercent, NumberRtpPercent } from '@/utils/math'
import { getPlayerDetails, getPlayerGold, getBetGearDetails, setPlyerType } from '@/api/player'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const tableRef = ref<any>()
watch(
  () => props.show,
  async (show) => {
    data.dayIndex = 1
    data.dayTableIndex = 4
    data.detailType = 1
    data.gameType = -1
    if (show) {
      changeTime(4)
      getSearchList(false)
      nextTick(() => {
        tableRef.value.clearSort()
      })
    }
  },
)

// 数据
const data = reactive({
  userOldInfo: {} as any,
  userInfo: {} as any,
  date: getWeek(0),
  game_id: -1,
  loadingInfo: false,
  loadingChart: false,
  onlineXAxis: [] as string[],
  onlineSeries: [] as number[],
  gameType: -1,
  list: [] as any[],
  dayIndex: 1,
  dayTableIndex: 4,
  fields: [
    { label: '平台ID', key: 'account3d_id', value: 0, show: 1 },
    { label: '平台昵称', key: 'account3d', value: 0, },
    { label: '当前余额', key: 'amount', value: 0, show: 1 },
    { label: '创建时间', key: 'created_at_stamp', value: 0 },
    { label: '最后登录时间', key: 'last_login_stamp', value: 0, show: 1 },
    { label: '当前状态', key: 'is_online', value: 0 },
    { label: '三日登录次数', key: 'three_login_num', value: 0, show: 1 },
    { label: '总登录次数', key: 'total_login_num', value: 0 },
    { label: '今日局数', key: 'today_bet_count', value: 0, show: 1 },
    { label: '历史局数', key: 'total_bet_count', value: 0 },
    { label: '注册IP地址', key: 'user_first_login_ip', value: '', show: 1 },
    { label: '今日流水倍数', key: 'today_bet_multiple', value: 0, show: 1 },
    { label: '三日流水倍数', key: 'three_day_bet_multiple', value: 0 },
    { label: '当天押注', key: 'today_bet', value: 0, show: 1 },
    { label: '三日押注', key: 'three_day_bet', value: 0 },
    { label: '总押注', key: 'total_bet', value: 0, show: 1 },
    { label: '今日输赢', key: 'today_game_income', value: 0 },
    { label: '三日输赢', key: 'three_day_game_income', value: 0, show: 1 },
    { label: '历史输赢', key: 'total_game_income', value: 0 },
    { label: '三日胜率', key: 'three_percent', value: 0, show: 1 },
    { label: '历史胜率', key: 'history_percent', value: 0 },
    { label: '留存天数', key: 'retention_day', value: 0, show: 1 },
  ],
  detailType: 1,
  gameList: [] as any,
  sortValue: {
    column: {} as any,
    order: '',
    prop: '',
  },
  total_bet: 0,
  gearList: [] as any,
  gearOldList: [] as any,
  gearFields: [
    { label: '游戏名称', prop: 'game_id', value: '', width:'120',detailType: 1 , show: true, },
    { label: '游戏名称', prop: 'game_id', value: '', width:'120',detailType: 2 , show: true },
    { label: '历史下注', prop: 'total_bet', value: 0, width:'',detailType: 1, sort: true, show: true  },
    { label: '下注次数', prop: 'total_bet_count', value: '', width:'',detailType: 1, sort: true, show: true  },
    { label: '历史输赢', prop: 'total_game_income', value: '', width:'',detailType: 1, sort: true, show: true  },
    { label: '历史RTP', prop: 'rtp', value: '', width:'',detailType: 1, show: true  },
    { label: '上次游戏登录地区', prop: 'region', value: '', width:'',detailType: 1, show: true  },
    { label: '下注额度/占比', prop: 'percentage', value: '', width:'165',detailType: 2, show: true, tips:'筛选日期内此游戏的下注额度，占比：此游戏下注额度/日期内所有游戏总下注'  },
    { label: '下注次数', prop: 'sum_bet_count', value: '', width:'140',detailType: 2, sort: true, show: true, tips:'筛选日期内，在此游戏的下注次数'  },
    { label: '下注档位', prop: 'user_gear', value: '', width:'120',detailType: 2, show: true, tips:'筛选日期内，在此游戏的下注金额档位列举，去重；'  },
    { label: '下注档位占比', prop: 'proportion', value: '', width:'150',detailType: 2, show: true, tips:'筛选日期内，每个下注档位的下注次数/总下注次数*100%，用，间隔；格式与“下注档位”保持一致顺序'  },
    { label: '游戏输赢', prop: 'total_income', value: '', width:'145',detailType: 2, sort: true, show: true, tips:'筛选日期内，玩家在此游戏的输赢情况；'  },
  ],
})

const getSearchList = async (show: boolean,table?:boolean) => {
  data.onlineXAxis = []
  data.onlineSeries = []
  data.loadingInfo = true
  let details = await getPlayerDetails({ id: props.checkedItem.uid }), dataObj = {} as any, keyData = [] as any;
  Object.assign(dataObj, details.data.user_info, details.data)
  Object.assign(data.userInfo, details.data.user_info)
  Object.assign(data.userOldInfo, details.data.user_info)
  console.log('玩家详情', dataObj, data.userInfo);
  // 详情数据
  keyData = Object.keys(dataObj)
  data.fields.forEach((item: any) => {
    keyData?.forEach((key: string) => {
      if (key == item.key) {
        item.value = dataObj[key]
        if (item.key == 'created_at_stamp') {
          item.value = setTimestampTime(dataObj['created_at_stamp'])
        }
        if (item.key == 'last_login_stamp') {
          item.value = setTimestampTime(dataObj['last_login_stamp'])
        }
        if (item.key == 'is_online') {
          item.value = selectToLabel(OnlineState, dataObj['is_online'])
        }
        if (item.key == 'user_first_login_ip') {
          item.value = dataObj['user_first_login_ip'] + '(' + dataObj['ip_country'] + ')'
        }
        if (item.key == 'amount' || item.key == 'today_bet' || item.key == 'three_day_bet' || item.key == 'total_bet' ||
          item.key == 'today_game_income' || item.key == 'three_day_game_income' || item.key == 'total_game_income') {
          item.value = BigWan(dataObj[key])
        }
      }
      // 胜率
      if (item.key == 'three_percent') {
        item.value = BigPercent(dataObj['three_day_win_bet_count'], dataObj['three_day_bet_count'])
      }
      if (item.key == 'history_percent') {
        item.value = BigPercent(dataObj['total_win_bet_count'], dataObj['total_bet_count'])
      }
    })
  })
  // 表格数据
  dataObj.game_data?.forEach((item: any) => {
    item.rtp = NumberRtpPercent(item.total_win, item.total_bet)
  })
  data.loadingInfo = false
  data.list = dataObj.game_data
  chooseGame(data.gameType)
  if (show) {
    ElMessage.success('刷新成功')
    if (data.sortValue.prop) {
      sortTable(data.sortValue)
    }
  }
}
// 玩家资产走势
const getGoldList = async () => {
  data.onlineXAxis = []
  data.onlineSeries = []
  data.loadingChart = true
  let gold = await getPlayerGold(setTimeValue({ id: props.checkedItem.uid, date: data.date, game_id: data.game_id }));
  data.loadingChart = false
  gold.data?.forEach((item: { save_time_stamp: number, after_settlement_money: number }) => {
    data.onlineXAxis.push(setTimestampTime(item.save_time_stamp))
    data.onlineSeries.push(BigWan(item.after_settlement_money))
  })
}
// 玩家投注栏位
const getBetGearList = async () => {
  data.onlineXAxis = []
  data.onlineSeries = []
  let res = await getBetGearDetails(setTimeValue({ id: props.checkedItem.uid, date: data.date}));
  res.data.game_data?.forEach((item:any)=> {
    item.show = true
    let income = [] as number[];
    item.user_gear?.forEach((second:any)=> {
      income.push(second.win - second.sum_bet)
    })
    item.total_income = ArrayReduce(income) //总输赢
  })
  data.gearList = res.data.game_data
  data.gearOldList = res.data.game_data
  data.total_bet = res.data.total_bet
  chooseGame(data.gameType)
}
// 设置玩家类型
const setUserType = ()=>{
  ElMessageBox.confirm(`确认是否修改玩家账号为【${selectToLabel(PlayerType,data.userInfo.test_type)}】？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await setPlyerType({
      id: props.checkedItem.uid,
      test_type:data.userInfo.test_type
    })
    ElMessage.success('操作成功')
    getSearchList(false)
  }).catch(() => { })
}

// 选择游戏tab
const handleClick = async (value: any) => {
  data.gameType = -1
  data.detailType = value.paneName
  chooseGame(-1)
  if(value.paneName==2){
    getBetGearList()
  }
}

// 排序
const sortTable = async (val: any) => {
  data.sortValue = val
  if(data.detailType==1){
    if (val.order == 'descending') {
      data.gameList = sortObjectArray(data.list, val.prop, 'desc')
    } else {
      data.gameList = sortObjectArray(data.list, val.prop, 'asc')
    }
  }else{
    if (val.order == 'descending') {
      data.gearList = sortObjectArray(data.gearList, val.prop, 'desc')
    } else {
      data.gearList = sortObjectArray(data.gearList, val.prop, 'asc')
    }
  }
}

// 刷新
const refresh = throttle((type: number) => {
  getSearchList(true)
  getGoldList()
  getBetGearList()
}, 3000)
// 设置快捷查询时间
const changeTime = throttle((type: number) => {
  if (data.dayIndex == type) return false
  data.dayIndex = type
  switch (type) {
    case 1:
      data.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.date = getWeek(-1)
      break;
    case 4:
      data.date = getWeek(0)
      break;
    case 5:
      data.date = getMonth(0)
      break;
    case 6:
      data.date = getMonth(-1)
      break;
  }
  getGoldList()
}, 1000)
const changeTableTime = throttle((type: number) => {
  if (data.dayTableIndex == type) return false
  data.dayTableIndex = type
  switch (type) {
    case 1:
      data.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.date = getWeek(-1)
      break;
    case 4:
      data.date = getWeek(0)
      break;
    case 5:
      data.date = getMonth(0)
      break;
    case 6:
      data.date = getMonth(-1)
      break;
  }
  getBetGearList()
}, 1000)

// 筛选游戏
const chooseGame = async (val: any) => {
  // 历史信息
  if(data.detailType == 1){
    data.gameList = []
    if (val != -1) {
      data.list?.forEach((item: any) => {
        if (item.game_id != val) {
          item.show = false
        } else {
          item.show = true
        }
      })
    } else {
      data.list?.forEach((item: any) => {
        item.show = true
      })
    }
    data.list?.forEach((item: any) => {
      if (item.show) {
        data.gameList.push(item)
      }
    })
  }else{
    data.gearList = []
    if (val != -1) {
      data.gearOldList?.forEach((item: any) => {
        if (item.game_id != val) {
          item.show = false
        } else {
          item.show = true
        }
      })
    } else {
      data.gearOldList?.forEach((item: any) => {
        item.show = true
      })
    }
    data.gearOldList?.forEach((item: any) => {
      if (item.show) {
        data.gearList.push(item)
      }
    })
  }
}

const emit = defineEmits(['onHideDetails'])
// 取消
const handleClose = async () => {
  data.userInfo = {} as any
  data.gameList = [] as any[]
  data.gearList = [] as any[]
  data.gearOldList = [] as any[]
  data.fields = [
    { label: '平台ID', key: 'account3d_id', value: 0, show: 1 },
    { label: '平台昵称', key: 'account3d', value: 0, },
    { label: '当前余额', key: 'amount', value: 0, show: 1 },
    { label: '创建时间', key: 'created_at_stamp', value: 0 },
    { label: '最后登录时间', key: 'last_login_stamp', value: 0, show: 1 },
    { label: '当前状态', key: 'is_online', value: 0 },
    { label: '三日登录次数', key: 'three_login_num', value: 0, show: 1 },
    { label: '总登录次数', key: 'total_login_num', value: 0 },
    { label: '今日局数', key: 'today_bet_count', value: 0, show: 1 },
    { label: '历史局数', key: 'total_bet_count', value: 0 },
    { label: '注册IP地址', key: 'user_first_login_ip', value: '', show: 1 },
    { label: '今日流水倍数', key: 'today_bet_multiple', value: 0, show: 1 },
    { label: '三日流水倍数', key: 'three_day_bet_multiple', value: 0 },
    { label: '当天押注', key: 'today_bet', value: 0, show: 1 },
    { label: '三日押注', key: 'three_day_bet', value: 0 },
    { label: '总押注', key: 'total_bet', value: 0, show: 1 },
    { label: '今日输赢', key: 'today_game_income', value: 0 },
    { label: '三日输赢', key: 'three_day_game_income', value: 0, show: 1 },
    { label: '历史输赢', key: 'total_game_income', value: 0 },
    { label: '三日胜率', key: 'three_percent', value: 0, show: 1 },
    { label: '历史胜率', key: 'history_percent', value: 0 },
    { label: '留存天数', key: 'retention_day', value: 0, show: 1 },
  ]
  emit('onHideDetails', false)
}
</script>
<style lang="scss" scoped>
.showColor {
  background-color: var(--el-menu-hover-bg-color);
}

.contentData {
  border: 1px solid #666666;
}

.flexStartDetween {
  padding: 10px;
  font-size: 14px;

  .flexWrapDownRight {
    height: 390px;
  }

  background-color: var(--background);

  .itemData {
    height: 35px;
    line-height: 35px;
    margin-right: 5px;

    .width40 {
      font-weight: 600;
      border-right: 1px solid #fff;
    }
  }

  .titleData {
    .width30 {
      width: 33%;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
    }

    .chooseTitle {
      color: green;
    }
  }

  .dataType{
    position: absolute;
    top: -50px;
    left: 5px
  }
}
</style>
